package com.saascloud.web.core.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.saascloud.core.exception.GlobalErrorCode;
import com.saascloud.core.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 全局响应结果（ResponseBody）处理器
 */
@RestControllerAdvice()
@Slf4j
public class GlobalResponseBodyHandler implements ResponseBodyAdvice {

    @Value("${saas.resp.body.wrapper.package:com.saascloud}")
    private String baseWrapperPackage;

    private ConcurrentHashMap<MethodParameter, Boolean> wrapperMap = new ConcurrentHashMap<>();

    private static final byte[] byteArrays = new byte[0];

    public GlobalResponseBodyHandler() {
        log.info("......GlobalResponseBodyHandler init......");
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        Boolean wrap = wrapperMap.get(returnType);
        if (Objects.isNull(wrap)) {
            String pkg = returnType.getMethod().getDeclaringClass().getPackage().getName().toLowerCase();
            wrap = pkg.startsWith(baseWrapperPackage);
            wrapperMap.put(returnType, wrap);
        }
        return wrap;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return R.success(null);
        }
        if (body.getClass().equals(byteArrays.getClass()) || body instanceof R) {
            return body;
        }
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        // String类型不能直接包装，所以要进行些特别的处理或者通过configureMessageConverters处理
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVO里后，再转换为json字符串响应给前端
                response.setStatusCode(HttpStatus.OK);
                return objectMapper.writeValueAsString(R.success(body));
            } catch (JsonProcessingException e) {
                return R.error(GlobalErrorCode.INTERNAL_SERVER_ERROR);
            }
        }
        // 将原本的数据包装在ResultVO里
        R<Object> success = R.success(body);
        return success;
    }
}
